package blackstar.agent.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class IPUtil
{
	public final static String LOCAL_HOST = "127.0.0.1";

	private static String localIp = null;

	public static synchronized String getLocalIP()
	{
		if (localIp != null)
		{
			return localIp;
		}
		// ͨ��hostȥ��ȡ
		try
		{
			InetAddress addr = InetAddress.getLocalHost();
			byte[] ipAddr = addr.getAddress();
			String ipAddrStr = "";
			for (int i = 0; i < ipAddr.length; i++)
			{
				if (i > 0)
				{
					ipAddrStr += ".";
				}
				ipAddrStr += ipAddr[i] & 0xFF;
			}
			localIp = ipAddrStr;

			return localIp;
		} catch (UnknownHostException e)
		{
		}

		try
		{
			Enumeration<NetworkInterface> netInterfaces = NetworkInterface
					.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements())
			{
				NetworkInterface ni = netInterfaces.nextElement();
				Enumeration<InetAddress> ips = ni.getInetAddresses();
				while (ips.hasMoreElements())
				{
					InetAddress ip = ips.nextElement();
					if (!LOCAL_HOST.equals(ip.getHostAddress()))
					{
						localIp = ip.getHostAddress();
						return localIp;
					}
				}
			}
		} catch (SocketException e)
		{
		}

		localIp = LOCAL_HOST;
		return localIp;
	}
}
